<template>
  <div class="app-container">
    <el-button type="primary" @click="addGoods">添加</el-button>
    <el-table :data="dataList" style="width: 100%;margin-top: 30px;" v-loading.body="listLoading" border>
      <el-table-column align="center" label="序号" width="100">
        <template scope="scope">
          {{scope.row.index}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品名称" width="200">
        <template scope="scope">
          {{scope.row.goodsName}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="性别" width="200">
        <template scope="scope">
          {{scope.row.sex==0?'男士':'女士'}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品类别" width="200">
        <template scope="scope">
          {{scope.row.detailName}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品详情" width="200">
        <template scope="scope">
          <div v-for="it in scope.row.goodsImage.split(';')">
            <img :src="it" min-width="120" height="120" />
          </div>
          <!-- <img :src="scope.row.goodsPrice" min-width="120" height="120" /> -->

        </template>
      </el-table-column>
      <el-table-column align="center" label="商品价格" width="200">
        <template scope="scope">
          {{scope.row.goodsPrice}}
          <!-- <img :src="scope.row.goodsPrice" min-width="120" height="120" /> -->
        </template>
      </el-table-column>
      <el-table-column align="center" label="优惠价格" width="200">
        <template scope="scope">
          {{scope.row.goodsFavPrice}}
          <!-- <img :src="scope.row.goodsFavPrice" min-width="120" height="120" /> -->
        </template>
      </el-table-column>
      <el-table-column align="center" label="排序" width="200">
        <template scope="scope">
          {{scope.row.orderNum}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300">
        <template scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope)">下架</el-button>
        </template>
      </el-table-column>

    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
    </div>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑详情':'添加详情'">
      <el-form autoComplete="on" :model="item" label-width="80px" label-position="left" ref="goods" :rules="rules">

        <el-form-item label="性别" prop="sex">
          <el-select class="el-input" v-model="item.sex" placeholder="请选择">
            <el-option v-for="it in sexes" :key="it.value" :label="it.label" :value="it.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="品类" prop="categoryId">
          <el-select class="el-input" v-model="item.categoryId" placeholder="请选择" @change="categoryChanged">
            <el-option v-for="it in categoryArray" :key="it.value" :label="it.label" :value="it.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="品类种类" prop="categoryDetailId">
          <el-select class="el-input" v-model="item.categoryDetailId" placeholder="请选择">
            <el-option v-for="it in categoryDetailArray" :key="it.value" :label="it.label" :value="it.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品名称" prop="goodsName">
          <el-input autoComplete="on" name="goodsName" v-model="item.goodsName" placeholder="商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload action="/api/shop/file/upload" list-type="picture-card" :headers="getToken()"
            :on-success="uploadSuccess" :onError="uploadError" :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品价格" prop="price">
          <el-input autoComplete="on" name="price" v-model="item.price" placeholder="商品价格"></el-input>
        </el-form-item>

        <el-form-item label="优惠卖价" prop="favPrice">
          <el-input autoComplete="on" name="favPrice" v-model="item.favPrice" placeholder="优惠卖价"></el-input>
        </el-form-item>

        <el-form-item label="款式" prop="style">
          <el-input autoComplete="on" name="style" v-model="item.style" placeholder="款式"></el-input>
        </el-form-item>

        <el-form-item label="尺码" prop="size">
          <el-input autoComplete="on" name="size" v-model="item.size" placeholder="尺码"></el-input>
        </el-form-item>

        <el-form-item label="排序" prop="orderNum">
          <el-input autoComplete="on" name="orderNum" v-model="item.orderNum" placeholder="排序"></el-input>
        </el-form-item>

      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmAdd">确认</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogImageVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

  </div>
</template>

<script>
  import { all } from 'api/shopCagegory'
  import { save, page, del } from 'api/shopGoods'
  import { token, getDetail } from 'api/shopCategoryDetail'
  import { client } from '../../../utils/oss.js'
  export default {
    data() {
      return {
        item: {},
        goods: {},
        categoryArray: [],
        categoryDetailArray: [],
        dialogVisible: false,
        dialogType: 'new',
        listLoading: false,
        checkStrictly: false,
        total: 10,
        dataList: [],
        imageUrls: [],
        dialogImageUrl: '',
        dialogImageVisible: false,
        defaultProps: {
          children: 'children',
          label: 'title'
        },
        listQuery: {
          page: 1,
          limit: 20,
          name: undefined
        },
        sexes: [{
          value: '0',
          label: '男士'
        }, {
          value: '1',
          label: '女士'
        }],
        rules: {
          sex: [{
            required: true,
            message: '请选择性别',
            trigger: 'blur'
          }],
          categoryId: [{
            required: true,
            message: '请选择品类',
            trigger: 'blur'
          }],
          categoryDetailId: [{
            required: true,
            message: '请选择种类',
            trigger: 'blur'
          }],
          goodsName: [{
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }],
          price: [{
            required: true,
            message: '请输入商品价格',
            trigger: 'blur'
          }]
        }
      }
    },
    created() {
      this.getCategory()
      this.getlist()
    },
    methods: {
      handleRemove(file, fileList) {
        var re = -1;

        for (var ix in this.imageUrls) {
          var index = this.imageUrls[ix].lastIndexOf(file.response.data)
          if (index >= 0) {
            re = ix;
            break
          }
        }
        if (re > -1) {
          this.imageUrls.splice(0, re);
        }
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogImageVisible = true;
      },
      getlist() {
        this.listLoading = true
        page(this.listQuery).then(response => {
          var data = response.data
          this.dataList = data.rows;
          this.total = data.total;
          this.listLoading = false;
          for (var ix in this.dataList) {
            this.dataList[ix].index = parseInt(ix, 10) + 1;
          }
          console.log(data)
          this.listLoading = false
        })
      },
      getCategory() {
        var that = this
        that.categoryArray = []
        all().then((res) => {
          if (res.status == 200) {
            for (var ix in res.data) {
              that.categoryArray.push({ "value": res.data[ix].id, "label": res.data[ix].name })
            }
          }
          console.log(res)
        })
      },
      getCategoryDetail(categoryId) {
        var that = this;
        that.categoryDetailArray = []
        getDetail(categoryId).then(res => {
          var sex = that.item.sex
          var data = res.data
          for (var ix in data) {
            if (data[ix].name == sex) {
              for (var ic in data[ix].children) {
                var child = data[ix].children[ic]
                that.categoryDetailArray.push({ "value": child.link, "label": child.name })
              }
              break;
            }
          }

          console.log(data)
        })
      },
      categoryChanged() {
        this.getCategoryDetail(this.item.categoryId)
      },
      handleEdit(scope) {
        var data = this.dataList[scope.row.index - 1]
        this.item.orderNum = data.orderNum
        this.item.id = data.id
        this.item.status = 1
        this.dialogType = 'edit'
        this.dialogVisible = true
      },
      handleDel(scope) {
        this.$confirm('确定下架该商品吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          scope.row.status = 0
          del(scope.row.id).then(res => {
            if (res.status == 200) {
              this.$success("下架成功")
              this.getlist()
            } else {
              this.$error(res.message)
            }
          })

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消下架'
          });
        });
      },

      addGoods() {
        this.dialogType = 'new'
        this.dialogVisible = true
        this.item = {}
        this.item.id = ''
        this.item.status = 1
      },
      // 上传成功后的回调
      uploadSuccess(response, file, fileList) {
        if (response.status == 200) {
          this.imageUrls.push('http://localhost:9762/api/shop/file/image/' + response.data)
        } else {
          this.$error('上传失败')
        }
      },
      // 上传错误
      uploadError(response, file, fileList) {
        console.log('上传失败，请重试！')
      },
      getToken() {
        var data = { 'token': token().token }
        return data
      },
      //上传到阿里云
      async fnUploadRequest(file) {
        const self = this
        let files = file.file,
          point = files.name.lastIndexOf('.'),
          suffix = files.name.substr(point),
          fileName = files.name.substr(0, point),
          date = Date.parse(new Date()),
          fileNames = `${fileName}_${date}${suffix}`;

        //fileNames上传文件的名称
        //file.file上传文件的内容
        client().put(fileNames, file.file).then(result => {
          //下面是如果对返回结果再进行处理，根据项目需要
          console.log(result)
          self.$message({
            message: '上传成功',
            type: 'success'
          });
        }).catch(err => {
          self.$message.error('上传失败');
        })
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
      },
      confirmAdd() {
        this.$refs.goods.validate(valid => {
          this.goods.goodsName = this.item.goodsName
          this.goods.goodsCategory = this.item.categoryDetailId
          this.goods.goodsStatus = 1
          this.goods.goodsPrice = this.item.price
          this.goods.goodsFavPrice = this.item.favPrice
          this.goods.goodsImage = this.imageUrls.join(';')
          this.goods.goodsSize = this.item.size
          this.goods.goodsStyle = this.item.style
          this.goods.orderNum = this.item.orderNum
          save(this.goods).then(res => {
            if (res.status == 200) {
              this.dialogType = 'edit'
              this.dialogVisible = false
              this.$success('保存成功')
              this.getlist()
            } else {
              this.$error('保存失败')
            }
          })
        })

      }
    },
  }
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>